package com.summer.client;


import com.summer.handler.UserClientHandler;
import com.sunmmer.service.JSONSerializer;
import com.sunmmer.service.RpcEncoder;
import com.sunmmer.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RPCConsumer {
    //1、创建一个线程池对象--它要处理我们自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    //2、声明一个自定义事件处理器 UserClientHandler
    private static UserClientHandler userClientHandler;

    //3、初始化客户端（创建连接池 bootstrap ）
    public static void initClient() throws InterruptedException {
        //初始化
         userClientHandler = new UserClientHandler();
         //创建连接池对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        //创建客户端到引导对象
        Bootstrap bootstrap = new Bootstrap();
        //配置启动引导对象
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                //监听handler
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取Pipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });

        //连接服务端
        ChannelFuture sync = bootstrap.connect("127.0.0.1", 8999).sync();

    }

    //使用jdk的动态代理创建对象
    //serviceClass接口类型 根据那个接口生成子类代理对象
    public static Object createProxy(Class<?> serviceClass, final String providerParam){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] objs) throws Throwable {
                        //初始化客户端client
                        if(userClientHandler == null){
                            initClient();
                        }
                        //2、给userClientHandler 设置参数
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(String.valueOf(System.currentTimeMillis()));
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(objs);
                        System.out.println("请求内容："+rpcRequest);
                        userClientHandler.setRpcRequest(rpcRequest);
                        //使用线程池。开启一个线程处理call操作，返回结果
                        Object result = executorService.submit(userClientHandler).get();
                        return result;
                    }
                });
    }
}
